package com.itheima.project.basic;

import com.itheima.project.constant.SuperConstant;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.validation.Create;
import com.itheima.project.validation.Update;
import com.itheima.project.vo.security.UserVo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

/**
 * @ClassName AuthUser.java
 * @Description 自定认证用户
 */
@Data
@NoArgsConstructor
public class UserAuth implements UserDetails {

    private String id;

    private String username;

    private String password;

    private Boolean enabled;

    private String clientId;

    private Long enterpriseId;

    private String openId;

    private Collection<SimpleGrantedAuthority> authorities;

    private Set<String> resources;

    private Set<String> roles;

    private String mobile;

    public UserAuth(UserVo userVo) {
        this.setId(userVo.getId().toString());
        this.setUsername(userVo.getUsername());
        this.setPassword(userVo.getPassword());
        this.setEnabled(SuperConstant.YES.equals(userVo.getEnableFlag()));
        this.setClientId(userVo.getClientId());
        if (!EmptyUtil.isNullOrEmpty(userVo.getResources())) {
            authorities = new ArrayList<>();
            userVo.getResources().forEach(resourcesLabel -> authorities.add(new SimpleGrantedAuthority(resourcesLabel)));
        }
        this.setResources(userVo.getResources());
        this.setRoles(userVo.getRoles());
        this.setEnterpriseId(userVo.getEnterpriseId());
        this.setOpenId(userVo.getOpenId());
        this.setMobile(userVo.getMobile());

    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
